﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace GBH.Models.Dao
{
    public class MaterialDao
    {
        public material SelectMat(string matno)
        {
            using (var db = new GBHEntities())
            {
                material matexisting = db.materials.Where(m => m.mmatno == matno).FirstOrDefault();
                return matexisting;
            }
        }

        public bool SaveMats(List<material> mats)
        {
            try
            {
                foreach (var mat in mats)
                {
                    SaveMat(mat);
                }
                return true;
            }
            catch (Exception)
            {

                return false;
            }

        }


        public bool SaveMat(material mat)
        {
            using (var db = new GBHEntities())
            {
                material matexisting = db.materials.Where(m => m.mmatno == mat.mmatno).FirstOrDefault();
                if (matexisting == null)
                {
                    db.materials.Add(mat);
                }
                else
                {
                    matexisting.isEnable = mat.isEnable;
                    matexisting.packageunit = mat.packageunit;
                    matexisting.quantitypersetunit = mat.quantitypersetunit;
                    matexisting.setunit = mat.setunit;
                    matexisting.setunitsize = mat.setunitsize;
                    matexisting.sizeunit = mat.sizeunit;
                    matexisting.mnamethai = mat.mnamethai;
                    matexisting.npibarcode = mat.npibarcode;
                }
                return db.SaveChanges() > 0;
            }
        }

        public material GetConvertUnit(string NawaMatno)
        {
            using (var db = new GBHEntities())
            {
                material matexisting = db.materials.Where(m => m.npibarcode == NawaMatno).FirstOrDefault();
                return matexisting;
            }
        }

        public bool ClearMats()
        {
            using (var db = new GBHEntities())
            {
                var branch = db.Database.ExecuteSqlCommand("TRUNCATE TABLE [material]");
                return branch > 0;
            }
        }
    }
}